﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;

namespace WebTest
{
    /// <summary>
    /// 离线消息
    /// </summary>
    public class MessageInfo
    {
        public MessageInfo(DateTime _MsgTime, ArraySegment<byte> _MsgContent)
        {
            MsgTime = _MsgTime;
            MsgContent = _MsgContent;
        }
        public DateTime MsgTime { get; set; }
        public ArraySegment<byte> MsgContent { get; set; }
    }
    public class SocketStr
    {
        /// <summary>
        /// 发送人
        /// </summary>
        public string SendUser { get; set; }

        /// <summary>
        /// 接收人如:Tom,Dante ;多个则不填写或则为all
        /// </summary>
        public string ToUser { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
    }
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        //用户连接池
        private static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();
        //离线消息池
        private static Dictionary<string, List<MessageInfo>> MESSAGE_POOL = new Dictionary<string, List<MessageInfo>>();

        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(ProcessChat);
            }
        }

        //发送过来的内容格式为"用户名称"|"消息"
        private async Task ProcessChat(AspNetWebSocketContext context)
        {
            WebSocket socket = context.WebSocket;
            string user = context.QueryString["user"].ToString();
            string content = string.Empty;
            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]);
            try
            {
                #region 用户添加连接池
                //第一次open时，添加到连接池中
                if (!CONNECT_POOL.ContainsKey(user))
                {
                    CONNECT_POOL.Add(user, socket);//不存在，添加

                    foreach (var item in CONNECT_POOL)
                    {
                        content = string.Format("{0}在{1}加入了聊天", user, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        buffer = GetSendByte(user, "", content);
                        await item.Value.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                }
                else
                {
                    if (socket != CONNECT_POOL[user])//当前对象不一致，更新
                    {
                        CONNECT_POOL[user] = socket;
                    }
                }
                #endregion

                #region 离线消息处理
                if (MESSAGE_POOL.ContainsKey(user))
                {
                    List<MessageInfo> msgs = MESSAGE_POOL[user];
                    foreach (MessageInfo item in msgs)
                    {
                        await socket.SendAsync(item.MsgContent, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    MESSAGE_POOL.Remove(user);//移除离线消息
                }
                #endregion

                string descUser = string.Empty;//目的用户
                while (true)
                {
                    var nowTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    if (socket.State == WebSocketState.Open)
                    {
                        WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                        #region 消息处理（字符截取、消息转发）
                        try
                        {
                            #region 关闭Socket处理，删除连接池
                            if (socket.State != WebSocketState.Open)//连接关闭
                            {
                                if (CONNECT_POOL.ContainsKey(user))
                                {  //删除连接池
                                    CONNECT_POOL.Remove(user);
                                    //用户离开通知 
                                    foreach (var item in CONNECT_POOL)
                                    {
                                        content = string.Format("{0}在{1}离开了", user, nowTimeStr);
                                        buffer = GetSendByte(user, "", content);
                                        await item.Value.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                                    }
                                }
                                break;
                            }
                            #endregion

                            string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);//发送过来的消息
                            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                            var socketModel = jss.Deserialize<SocketStr>(userMsg);
                            if (socketModel.ToUser != "" && !socketModel.ToUser.ToLower().Equals("all"))
                            {

                                content = string.Format("{0}在{1}说:{2}", socketModel.SendUser, nowTimeStr, socketModel.Content);
                                buffer = GetSendByte(user, "", content);
                            }
                            if (socketModel.ToUser != "" && !socketModel.ToUser.ToLower().Equals("all"))
                            {
                                //发送目标用户
                                var toUsers = socketModel.ToUser.Split(new char[','],
                                     StringSplitOptions.RemoveEmptyEntries).ToList();
                                foreach (var item in toUsers)
                                {
                                    content = string.Format("{0}在{1}对{2}说:{3}", socketModel.SendUser, nowTimeStr, item, socketModel.Content);
                                    buffer = GetSendByte(user, item, content);
                                    if (CONNECT_POOL.ContainsKey(item))//判断客户端是否在线
                                    {
                                        WebSocket destSocket = CONNECT_POOL[item];//目的客户端
                                        if (destSocket != null && destSocket.State == WebSocketState.Open)
                                            await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                                    }
                                    else
                                    {
                                        Task.Run(() =>
                                        {
                                            if (!MESSAGE_POOL.ContainsKey(item))//将用户添加至离线消息池中
                                                MESSAGE_POOL.Add(item, new List<MessageInfo>());
                                            MESSAGE_POOL[item].Add(new MessageInfo(DateTime.Now, buffer));//添加离线消息
                                        });
                                    }
                                }
                            }
                            else
                            {
                                //群发
                                foreach (var item in CONNECT_POOL)
                                {
                                    content = string.Format("{0}在{1}说:{2}", socketModel.SendUser, nowTimeStr, socketModel.Content);
                                    buffer = GetSendByte(user, "", content);
                                    await item.Value.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                                }
                            }

                            //if (!string.IsNullOrEmpty(descUser))
                            //{

                            //    if (CONNECT_POOL.ContainsKey(descUser))//判断客户端是否在线
                            //    {
                            //        WebSocket destSocket = CONNECT_POOL[descUser];//目的客户端
                            //        if (destSocket != null && destSocket.State == WebSocketState.Open)
                            //            await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                            //    }
                            //    else
                            //    {
                            //        Task.Run(() =>
                            //        {
                            //            if (!MESSAGE_POOL.ContainsKey(descUser))//将用户添加至离线消息池中
                            //                MESSAGE_POOL.Add(descUser, new List<MessageInfo>());
                            //            MESSAGE_POOL[descUser].Add(new MessageInfo(DateTime.Now, buffer));//添加离线消息
                            //        });
                            //    }
                            //}
                            //else
                            //{
                            //    //群发
                            //    foreach (var item in CONNECT_POOL)
                            //    {
                            //        await item.Value.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                            //    }
                            //}
                        }
                        catch (Exception exs)
                        {
                            //消息转发异常处理，本次消息忽略 继续监听接下来的消息
                        }
                        #endregion
                    }
                    else
                    {
                        break;
                    }
                }//while end
            }
            catch (Exception ex)
            {
                //整体异常处理
                if (CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Remove(user);
            }
        }
        /// <summary>
        /// 封装推送的数据
        /// </summary>
        /// <param name="sendUser">发送人</param>
        /// <param name="toUser">接收人:为空则为全部</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public ArraySegment<byte> GetSendByte(string sendUser, string toUser, string content)
        {
            List<string> onlineList = CONNECT_POOL.ToList().ConvertAll<string>(x => x.Key);
            var onlieModel = new
            {
                Count = onlineList.Count,
                Users = onlineList

            };
            var obj = new
            {
                SendUser = sendUser,
                ReceiveUser = toUser,
                Content = content,
                OnlineUser = onlieModel
            };
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return new ArraySegment<byte>(Encoding.UTF8.GetBytes(jss.Serialize(obj)));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}